//
//  SXHBaseScriptMessage.m
//  ZLZKBaseUtils
//
//  Created by sxh on 2020/12/14.
//

#import "SXHBaseScriptMessage.h"
#import "JSBUtil.h"
#import <WebKit/WebKit.h>

@interface SXHBaseScriptMessage()
{
    WKWebView *_webview;
    NSDictionary *_dict;
    CallBack _completionHandler;
    UInt64 lastCallTime;
    NSString *jsCache;
    bool isPending;
    bool isDebug;
}
@end

@implementation SXHBaseScriptMessage

- (instancetype)initWithWebview:(WKWebView*)webview dict:(NSDictionary *)dict completionHandler:(CallBack)completionHandler {
    if (self = [super init]) {
        _webview = webview;
        _dict = dict;
        _completionHandler = completionHandler;
        jsCache = @"";
    }
    return self;
}

- (NSString *)name{
    if ([_dict.allKeys containsObject:@"data"]) {
        NSDictionary *data = _dict[@"data"];
        if ([data.allKeys containsObject:@"name"]) {
            return data[@"name"];
        }
    }
    return @"";
}

- (id)userInfo {
    if ([_dict.allKeys containsObject:@"data"]) {
        NSDictionary *data = _dict[@"data"];
        if ([data.allKeys containsObject:@"userInfo"]) {
            return data[@"userInfo"];
        }
    }
    return @{};
}

/// 回调函数
- (void)callbackWithRet:(id)ret {
    
    NSDictionary *resultDict = @{@"code": @"200", @"message": [NSString stringWithFormat:@"调用%@方法成功", self.name], @"data": ret};
//    NSString *result = [JSBUtil objToJsonString:@{@"code":@"0",@"data":resultDict}];
    
    if ([_dict.allKeys containsObject:@"_dscbstub"]) {
        
        [self scriptToJS: resultDict];
    }
}

// 执行js
- (NSString *)scriptToJS:(id)str {
    
    NSMutableDictionary*result =[NSMutableDictionary dictionaryWithDictionary:@{@"code":@-1,@"data":@""}];
    NSDictionary *args = _dict;
    NSString *value = @"";
    
    id arg = args[@"data"];
    if(arg == [NSNull null]){
        arg = nil;
    }
    
    NSString *cb;
    
    do{
        if(args && (cb = args[@"_dscbstub"])){
            __weak typeof(self) weakSelf = self;
            NSString *del = @"";
            
            result[@"code"] = @0;
            
            if(str != nil){
                
                result[@"data"] = str;
            }
            
            value = [JSBUtil objToJsonString:result];
            
            value = [value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

            del = [@"delete window." stringByAppendingString:cb];
            
            NSString *js=[NSString stringWithFormat:@"try {%@(JSON.parse(decodeURIComponent(\"%@\")).data);%@; } catch(e){};", cb,(value == nil) ? @"" : value, del];
            __strong typeof(self) strongSelf = weakSelf;
            @synchronized(self)
            {
                UInt64 t = [[NSDate date] timeIntervalSince1970] * 1000;
                jsCache = [jsCache stringByAppendingString:js];
                if(t - lastCallTime < 50){
                    if(!isPending){
                        [strongSelf evalJavascript: 50];
                        isPending = true;
                    }
                }else{
                    [strongSelf evalJavascript: 0];
                }
            }
            break;
        }
    } while(0);
    
    return [JSBUtil objToJsonString:result];
}

- (void)evalJavascript:(int)delay{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
        @synchronized(self){
            if([self->jsCache length] != 0){
                [self->_webview evaluateJavaScript: self->jsCache completionHandler:nil];
                self->isPending = false;
                self->jsCache = @"";
                self->lastCallTime = [[NSDate date] timeIntervalSince1970] * 1000;
            }
        }
    });
}

@end
